//
//  PurchaseUploadData.swift
//  GhostWorld
//
//  Created by Kam on 2018/6/18.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation
import CoreData

private let entityName = CoreDataEntityName.purchaseUploadData.rawValue
private let context = CoreDataHelper.getContext()

enum PurchaseType: Int16 {
  case token = 0
  case premium = 1
}

enum PurchasePlatfrom: Int16 {
  case iap = 0
  case alipay = 1
  case wechat = 2
}

extension PurchaseUploadData {
  func uploadToServer() {
    let body: [String : Any] = [
      "platform": platform,
      "transaction_json": transaction_json ?? "",
      "transaction_id": transaction_id!
    ]
    switch PurchaseType(rawValue: purchase_type)! {
    case .token:
      API.shared.requestAPI (
        APIURLStrings.purchaseToken(tokenIdentifier: Int(ref_id)),
        method: .post,
        body: body,
        header: API.shared.memeberHeader,
        successCallback: { json in
          
          loggingPrint("[Token purchase info uploaded] tokenID: \(self.ref_id), transactionID: \(self.transaction_id!)")
          
          context.delete(self)
          try! context.save()
          
          let listenerTotalTokenCount = json["total_coins"].intValue
          let notificationObject = UploadTokenPurchaseInfoNotificationObject(
            listenerTotalTokenCount: listenerTotalTokenCount
          )
          let userInfo = [UploadTokenPurchaseInfoNotificationObject.key: notificationObject]
          NotificationCenter.default.post (
            name: .uploadTokenPurchaseInfoSuccess,
            object: nil,
            userInfo: userInfo
          )
      }, errorCallback: { (message, code) in
        loggingPrint("Upload purchase to server failed! \(message)")
      })
    case .premium:
      // MARK: - [WARNING]: Handle premium
      break
    }
  }
}

extension PurchaseUploadData {
  static func save(platform: PurchasePlatfrom, type: PurchaseType, refID: Int, transactionJSON: String, transactionID: String) {
    let uploadData = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! PurchaseUploadData
    uploadData.id = NSUUID().uuidString
    uploadData.platform = platform.rawValue
    uploadData.purchase_type = type.rawValue
    uploadData.ref_id = Int16(refID)
    uploadData.transaction_json = transactionJSON
    uploadData.transaction_id = transactionID
    
    try! context.save()
  }
}
